Vue.component('add-project', {//添加项目
    template: `<el-dialog title="添加项目" :visible.sync="visibleDialog" width="700px">
    <el-form ref="contract" :model="form" :rules="rules" :inline-message="true">
        <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="项目名称">
                <el-form-item prop="Project_Name">
                    <el-input v-model.trim="form.Project_Name" placeholder="请输入项目名称"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="履约金额">
                <el-form-item prop="Performance_Amount">
                    <el-input v-model.trim="form.Performance_Amount" placeholder="请输入履约金额"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="合同期限">
                <el-form-item prop="Date">
                    <el-date-picker prefix-icon="el-icon-date" v-model="form.Date" clearable type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"  :default-time="['00:00:00', '23:59:59']" 
                        format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="项目备注">
                <el-form-item prop="Project_Notes">
                    <el-input v-model.trim="form.Project_Notes" placeholder="请输入项目备注"></el-input>
                </el-form-item>
            </el-descriptions-item>
        </el-descriptions>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm('contract')">提交</el-button>
    </span></el-dialog>`,
    props: ['visible'],
    data() {
        const validator = (rule, value, callback) => {
            if (!this.form.Date.length > 0) {
                callback(new Error('请选择合同期限'));
            } else {
                callback();
            }
        }
        return {
            visibleDialog: false,
            Icon: [],//图标库
            form: {
                Date: [],
                Project_Name: '',
                Project_Notes: '',
                Start_Date: '',
                End_Date: '',
                Performance_Amount: ''
            },
            rules: {
                Project_Name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
                Date: [{ required: true, validator, trigger: 'change' }]
            },
            loading: false,
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible;
        },
        visibleDialog(val) {
            this.$emit('update:visible', val);
        },
    },
    methods: {
        submitForm(formName) {
            const that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true;
                    if (that.form.Date && that.form.Date.length > 0) {
                        that.form.Start_Date = that.form.Date[0];
                        that.form.End_Date = that.form.Date[1];
                    }
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        type: 'POST',
                        data: {
                            Data: JSON.stringify({
                                Add: {
                                    business_project: [that.form],
                                }
                            })
                        },
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message.success("提交成功")
                                that.$emit('update:visible', false)
                                that.$emit('success')
                            } else {
                                that.$message.error("系统繁忙，请稍后再试")
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    })
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            })
        }
    },
})
Vue.component('edit-project', {//修改项目
    template: `<el-dialog title="修改项目" :visible.sync="visibleDialog" width="700px">
    <el-form ref="contract" :model="form" :rules="rules" :inline-message="true">
        <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="项目名称">
                <el-form-item prop="Project_Name">
                    <el-input v-model.trim="form.Project_Name" placeholder="请输入项目名称"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="履约金额">
                <el-form-item prop="Performance_Amount">
                    <el-input v-model.trim="form.Performance_Amount" placeholder="请输入履约金额"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="合同期限">
                <el-form-item prop="Date">
                    <el-date-picker prefix-icon="el-icon-date" v-model="form.Date" clearable type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"  :default-time="['00:00:00', '23:59:59']" 
                        format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="项目备注">
                <el-form-item prop="Project_Notes">
                    <el-input v-model.trim="form.Project_Notes" placeholder="请输入项目备注"></el-input>
                </el-form-item>
            </el-descriptions-item>
        </el-descriptions>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm('contract')">提交</el-button>
    </span></el-dialog>`,
    props: ['id', 'visible'],
    data() {
        const validator = (rule, value, callback) => {
            if (!this.form.Date.length > 0) {
                callback(new Error('请选择合同期限'));
            } else {
                callback();
            }
        }
        return {
            visibleDialog: false,
            Icon: [],//图标库
            form: {
                Date: [],
                Project_Name: '',
                Project_Notes: '',
                Start_Date: '',
                End_Date: '',
                Performance_Amount: ''
            },
            rules: {
                Project_Name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
                Date: [{ required: true, validator, trigger: 'change' }]
            },
            loading: false,
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible;
        },
        visibleDialog(val) {
            this.$emit('update:visible', val);
            if (val) {
                this.getData(this.id);
            }
        },
    },
    methods: {
        getData(Project_SerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                type: 'POST',
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                data: {
                    Data: "business_project",
                    Condition: "Project_SerialNumber='" + Project_SerialNumber + "'"
                },
                success: function (data) {
                    if (data.length == 1) {
                        let obj = data[0];
                        obj.Date = [data[0].Start_Date, data[0].End_Date]
                        that.form = obj;
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitForm(formName) {
            const that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true;
                    if (that.form.Date && that.form.Date.length > 0) {
                        that.form.Start_Date = that.form.Date[0];
                        that.form.End_Date = that.form.Date[1];
                    }
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        type: 'POST',
                        data: {
                            Data: JSON.stringify({
                                Modify: {
                                    business_project: [that.form],
                                }
                            })
                        },
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message.success("修改成功")
                                that.$emit('update:visible', false);
                                that.$emit('success');
                            } else {
                                that.$message.error("系统繁忙，请稍后再试")
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false;
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    })
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            })
        }
    },
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                SQLSerialNumber: "P_business_activity",
                PaginationNumber: 1,//页数
                RowAmount: 15,//每页数据条数
                Row_Status: '',
                Status: '',
                Activity_Name: '',
                ExtensionCondition: '',
                Project_SerialNumber: '',
            },
            total: 0,
            tableData: [],	//表格数据
            Row_Status: [{
                label: '全部',
                value: '',
            }, {
                label: '已发布',
                value: '2',
            }, {
                label: '未发布',
                value: '0',
            }],
            Status: [{
                label: '全部',
                value: '',
            }, {
                label: '未发布',
                value: '1',
            }, {
                label: '未开始',
                value: '2',
            }, {
                label: '进行中',
                value: '3',
            }, {
                label: '已结束',
                value: '4',
            }],
            isTree: true,
            defaultProps: {
                children: 'Children',
                label: 'Project_Name'
            },
            treeData: [],
            visibleAddProject: false,
            visibleEditProject: false,
            Project_SerialNumber: '',
            table:true
        }
    },
    mounted() {
        this.getData();
        this.getList(this.form);//前端分页
    },
    computed: {
        Type() {
            return function (str1, str2) {
                let d1 = +new Date();
                let d2 = +new Date(str1)
                let d3 = +new Date(str2)
                if (d1 < d2) {
                    return '未开始'
                } else if (d2 < d1 && d1 < d3) {
                    return '进行中'
                } else if (d3 < d1) {
                    return '已结束'
                }
            }
        }
    },
    methods: {
        success() {
            this.getData();
            this.getList(this.form);//前端分页
        },
        showTree() {
            this.isTree = !this.isTree
        },
        onSerach() {			//查询方法
            this.form.PaginationNumber = 1;
            this.getList(this.form)
        },
        Add() {
            window.location.href = './add.html'
        },
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form);
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form);
        },
        AddProject() {//新增项目
            this.visibleAddProject = true;
        },
        clickProject(command, node, data) {
            if (command == 'add') {//添加活动
                sessionStorage.setItem("Project_SerialNumber", data.Project_SerialNumber);
                window.location.href = './add.html?Project_SerialNumber=' + data.Project_SerialNumber;
            } else if (command == 'edit') {//修改项目
                this.Project_SerialNumber = data.Project_SerialNumber;
                this.visibleEditProject = true;
            } else if (command == 'remove') {//删除项目
                const that = this;
                this.$confirm('警告！此操作将删除该部门, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    let obj = deepClone(data);
                    obj.Row_Status = '1';
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        type: 'POST',
                        data: {
                            Data: JSON.stringify({
                                Modify: { business_project: [obj] },
                            })
                        },
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                that.getData();
                            } else {
                                that.$message.error("删除失败，请稍后再试")
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    })
                }).catch(() => { });
            }
        },
        getData() {//查询项目
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                type: 'POST',
                data: {
                    Data: "business_project",
                    Condition: "Row_Status='0'"
                },
                success: function (data) {
                    that.treeData = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList(form) {//换页方法
            const that = this
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent("%" + this.form.Activity_Name + "%,%" + this.form.Row_Status + "%")))
            let sql = "";
            if (data.Status != '') {
                if (data.Status == '1') {
                    sql = sql + " and business_activity.Row_Status = '0' ";
                } else if (data.Status == '2') {
                    sql = sql + " and business_activity.Start_Date > '" + getYMDHMSDate() + "'\r\n"
                } else if (data.Status == '3') {
                    sql = sql + " and '" + getYMDHMSDate() + "' BETWEEN business_activity.Start_Date and business_activity.End_Date\r\n"
                } else if (data.Status == '4') {
                    sql = sql + " and business_activity.End_Date < '" + getYMDHMSDate() + "'\r\n"
                }
            }
            if (data.Project_SerialNumber) {
                sql = sql + " and business_activity.Project_SerialNumber = '" + data.Project_SerialNumber + "'\r\n"
            }
            //操作
            data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                    that.table = false;
                    const timer = setTimeout(() => {
                        that.table = true;
                        clearTimeout(timer)
                    })
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        downloadTemplate(command) {
            if (command == 'Article') {
                window.location.href = './download/导入活动商品模板.xlsx';
            }
        },
        importTemplate(command) {
            if (command == 'Article') {
                window.location.href = './import.html';
            }
        },
        config(command, row) {
            const that = this;
            if (command == 'Edit') {
                this.Edit(row.Activity_SerialNumber)
            } else if (command == 'Remove') {
                this.Remove(row)
            } else if (command == 'ExportPointsLog') {
                //导出用户积分
                $.ajax({
                    headers: requestHeaders(),
                    type: 'POST',
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    data: {
                        SQLSerialNumber: 'A_business_member_points_log1',
                        Condition: window.btoa(unescape(encodeURIComponent(row.Activity_SerialNumber))),
                        ExtensionCondition: '',
                    },
                    success: function (data) {
                        if (data.length > 0) {
                            //创建xlsx结构
                            const wb = XLSX.utils.book_new();
                            const ws_data = [["手机号", "用户姓名", "所属活动", "用户部门", "剩余积分", "积分变动", "备注", "变动时间"]];
                            data.forEach(item => {
                                ws_data.push([
                                    item.Member_SerialNumber,
                                    item.Member_Name,
                                    item.Activity_Name,
                                    item.Department_Name,
                                    item.Remain_Points,
                                    item.Points,
                                    item.Notes ? item.Notes : item.Points_Title,
                                    getYMDHMSDate(item.Operation_Datetime)
                                ])
                            })
                            const ws = XLSX.utils.aoa_to_sheet(ws_data);
                            //合并逻辑
                            let obj = {};
                            ws_data.forEach((item, index) => {
                                if (obj[item[0]]) {
                                    obj[item[0]][1] = index;
                                    if (obj[item[0]][2][item[3]]) {
                                        obj[item[0]][2][item[3]][1] = index;
                                    } else {
                                        obj[item[0]][2][item[3]] = [index, index];
                                    }
                                } else {
                                    let obj1 = {};
                                    obj1[item[3]] = [index, index];
                                    obj[item[0]] = [index, index, obj1]
                                }
                            })
                            ws['!merges'] = [];
                            for (let key in obj) {
                                if (obj[key][0] != obj[key][1]) {
                                    ws['!merges'].push({
                                        s: { c: 0, r: obj[key][0] },
                                        e: { c: 0, r: obj[key][1] },
                                    }, {
                                        s: { c: 1, r: obj[key][0] },
                                        e: { c: 1, r: obj[key][1] },
                                    }, {
                                        s: { c: 2, r: obj[key][0] },
                                        e: { c: 2, r: obj[key][1] },
                                    })
                                    for (let key1 in obj[key][2]) {
                                        if (obj[key][2][key1][0] != obj[key][2][key1][1]) {
                                            ws['!merges'].push({
                                                s: { c: 3, r: obj[key][2][key1][0] },
                                                e: { c: 3, r: obj[key][2][key1][1] },
                                            }, {
                                                s: { c: 4, r: obj[key][2][key1][0] },
                                                e: { c: 4, r: obj[key][2][key1][1] },
                                            })
                                        }
                                    }
                                }
                            }
                            ws['!cols'] = [];
                            ws_data[0].forEach(item => {
                                ws['!cols'].push({ alignment: { horizontal: "center", vertical: 'center' }, wpx: 150 });
                            })
                            XLSX.utils.book_append_sheet(wb, ws, "积分记录");
                            XLSX.writeFile(wb, data[0].Activity_Name + '活动用户积分' + (+new Date()) + ".xlsx");
                            that.$message({
                                message: '已导出该活动用户积分记录！',
                                type: 'success'
                            })
                        } else {
                            that.$message({
                                message: '暂无可导出的数据',
                                type: 'warning'
                            })
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest, false, (Status) => {
                            if (Status == "error") {
                                that.$message.error("系统繁忙，请稍后再试");
                            }
                        });
                    },
                    dataType: "json"
                })
            } else if (command == 'ExportArticle') {
                $.ajax({
                    headers: requestHeaders(),
                    type: 'POST',
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    data: {
                        SQLSerialNumber: 'A_business_activity_article1',
                        Condition: window.btoa(unescape(encodeURIComponent(row.Activity_SerialNumber))),
                        ExtensionCondition: '',
                    },
                    success: function (data) {
                        if (data.length > 0) {
                            console.log(data);
                            //创建xlsx结构
                            const wb = XLSX.utils.book_new();
                            const ws_data = [["供应商经营商品流水号", "商品内码", "商品名称", "活动售价", "供货价", "库存", "状态", "供应商", "商品京东价", "商品京东链接", "规格内码", "规格名称", "规格京东价", "规格京东链接"]];
                            data.forEach(item => {
                                ws_data.push([
                                    item.Supplier_Article_SerialNumber,
                                    item.Article_SerialNumber,
                                    item.Article_Name,
                                    item.Activity_Unit_Price,
                                    item.Purchase_Unit_Price,
                                    item.Stock_Remain,
                                    item.Shelf == '0' ? '已上架' : '未上架',
                                    item.Supplier_Name,
                                    item.JDCOM_Unit_Price,
                                    item.JDCOM_URL,
                                    item.Article_Specifications_SerialNumber,
                                    item.Specifications_Name,
                                    item.JDCOM_Unit_Price1,
                                    item.JDCOM_URL1,
                                ])
                            })
                            const ws = XLSX.utils.aoa_to_sheet(ws_data);
                            ws['!cols'] = [];
                            ws_data[0].forEach(item => {
                                ws['!cols'].push({ alignment: { horizontal: "center" }, wpx: 150 });
                            })
                            XLSX.utils.book_append_sheet(wb, ws, "商品列表");
                            XLSX.writeFile(wb, row.Activity_Name + '活动商品列表' + (+new Date()) + ".xlsx");
                            that.$message({
                                message: '已导出该活动商品列表！',
                                type: 'success'
                            })
                        } else {
                            that.$message({
                                message: '暂无可导出的数据',
                                type: 'warning'
                            })
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest, false, (Status) => {
                            if (Status == "error") {
                                that.$message.error("系统繁忙，请稍后再试");
                            }
                        });
                    },
                    dataType: "json"
                })
            }
        },
        Edit(Activity_SerialNumber) {
            sessionStorage.setItem("Activity_SerialNumber", Activity_SerialNumber)
            window.location.href = './edit.html?Activity_SerialNumber=' + Activity_SerialNumber
        },
        Publish(row) {
            const that = this;
            this.$confirm('发布后该活动方案将无法修改, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                let obj = deepClone(row);
                obj.Row_Status = '2';
                $.ajax({
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/generalBusiness/generalSave`,
                    type: 'POST',
                    data: {
                        Data: JSON.stringify({
                            Modify: { business_activity: [obj] },
                            Add: { base_operation_log: [generateLog('发布活动--' + obj.Activity_Name, '平台端操作', 'business_activity', JSON.stringify({ Modify: { business_activity: [obj] } }))] }
                        })
                    },
                    success: function (res) {
                        if (res.Status === 'success') {
                            that.$message({
                                type: 'success',
                                message: '发布成功!'
                            });
                            that.getList(that.form);
                        } else {
                            that.$message.error("发布失败失败，请稍后再试")
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        that.loading = false;
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                })
            }).catch(() => { });
        },
        Remove(row) {
            const that = this
            this.$confirm('警告！此操作将作废该方案, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                let obj = deepClone(row);
                obj.Row_Status = '1';
                $.ajax({
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/generalBusiness/generalSave`,
                    type: 'POST',
                    data: {
                        Data: JSON.stringify({
                            Modify: { business_activity: [obj] },
                            Add: { base_operation_log: [generateLog('删除活动--' + obj.Activity_Name, '平台端操作', 'business_activity', JSON.stringify({ Modify: { business_activity: [obj] } }))] }
                        })
                    },
                    success: function (res) {
                        if (res.Status === 'success') {
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            that.getList(that.form);
                        } else {
                            that.$message.error("删除失败，请稍后再试")
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        that.loading = false
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                })
            }).catch(() => { });
        },
        handleNode(row) {//点击项目
            this.form.Project_SerialNumber = row.Project_SerialNumber
            this.getList(this.form);
        },
    },
})